package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

public class SystemLogAspect {

    @Setter
    private ISystemLogService systemLogService;
    //日志插入的操作,不要记录日志
    public void write(JoinPoint jp) throws JsonProcessingException {
        if (jp.getTarget() instanceof ISystemLogService){
            return;
        }

        System.out.println("日志写写写");
        SystemLog log=new SystemLog();
        log.setOptime(new Date());
        log.setOpuser((Employee) SecurityUtils.getSubject().getPrincipal());
        log.setFunction(jp.getTarget().getClass().getName()+":"+jp.getSignature().getName());
        log.setParams(new ObjectMapper().writeValueAsString(jp.getArgs()));

        //获取当前操作用户的IP地址
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        log.setOpip(requestAttributes.getRequest().getRemoteAddr());

        systemLogService.save(log);
    }
}
